import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:flutter/foundation.dart';
import 'native_video_cache_manager.dart';

/// APP生命周期管理器
/// 优化缓存在后台/前台切换时的行为
class AppLifecycleManager extends WidgetsBindingObserver {
  static AppLifecycleManager? _instance;
  static AppLifecycleManager get instance =>
      _instance ??= AppLifecycleManager._();

  AppLifecycleManager._();

  bool _isInitialized = false;
  AppLifecycleState _currentState = AppLifecycleState.resumed;
  Timer? _backgroundTimer;
  final Set<String> _activeUrls = <String>{};

  // 配置选项
  bool enableBackgroundCaching = true;
  Duration backgroundTimeout = const Duration(minutes: 5);
  bool pauseCachingInLowPowerMode = true;

  /// 初始化生命周期管理器
  void initialize() {
    if (_isInitialized) return;

    WidgetsBinding.instance.addObserver(this);
    _isInitialized = true;
    debugPrint('AppLifecycleManager: 初始化完成');
  }

  /// 注册正在缓存的URL
  void registerActiveUrl(String url) {
    _activeUrls.add(url);
    debugPrint(
        'AppLifecycleManager: 注册活跃缓存 - $url (总数: ${_activeUrls.length})');
  }

  /// 取消注册URL
  void unregisterActiveUrl(String url) {
    _activeUrls.remove(url);
    debugPrint(
        'AppLifecycleManager: 取消注册缓存 - $url (剩余: ${_activeUrls.length})');
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if (_currentState == state) return;

    final oldState = _currentState;
    _currentState = state;

    debugPrint(
        'AppLifecycleManager: 生命周期变化 $oldState -> $state (活跃缓存: ${_activeUrls.length})');

    switch (state) {
      case AppLifecycleState.paused:
        _handleAppPaused();
        break;
      case AppLifecycleState.resumed:
        _handleAppResumed();
        break;
      case AppLifecycleState.detached:
        _handleAppDetached();
        break;
      case AppLifecycleState.inactive:
        // iOS特有状态，暂时不处理
        break;
      default:
        break;
    }
  }

  /// 处理APP进入后台
  void _handleAppPaused() {
    if (!enableBackgroundCaching) {
      _pauseAllCaching();
      return;
    }

    // 启动后台定时器，超时后暂停缓存以节省资源
    _backgroundTimer?.cancel();
    _backgroundTimer = Timer(backgroundTimeout, () {
      debugPrint('AppLifecycleManager: 后台超时，暂停缓存以节省资源');
      _pauseAllCaching();
    });

    debugPrint(
        'AppLifecycleManager: APP进入后台，缓存将在${backgroundTimeout.inMinutes}分钟后暂停');
  }

  /// 处理APP恢复前台
  void _handleAppResumed() {
    _backgroundTimer?.cancel();
    _backgroundTimer = null;

    // 恢复所有缓存任务
    _resumeAllCaching();

    debugPrint('AppLifecycleManager: APP恢复前台，重启所有缓存任务');
  }

  /// 处理APP即将销毁
  void _handleAppDetached() {
    _backgroundTimer?.cancel();
    _backgroundTimer = null;

    // 停止所有缓存任务
    _stopAllCaching();

    debugPrint('AppLifecycleManager: APP即将销毁，停止所有缓存任务');
  }

  /// 暂停所有缓存（使用现有API）
  Future<void> _pauseAllCaching() async {
    for (final url in _activeUrls) {
      try {
        // 使用现有的stopCache方法暂停缓存
        await NativeVideoCacheManager.stopCache(url);
        debugPrint('AppLifecycleManager: 暂停缓存 - $url');
      } catch (e) {
        debugPrint('AppLifecycleManager: 暂停缓存失败 - $url: $e');
      }
    }
  }

  /// 恢复所有缓存（使用现有API）
  Future<void> _resumeAllCaching() async {
    for (final url in _activeUrls) {
      try {
        // 使用现有的startCache方法恢复缓存
        await NativeVideoCacheManager.startCache(url);
        debugPrint('AppLifecycleManager: 恢复缓存 - $url');
      } catch (e) {
        debugPrint('AppLifecycleManager: 恢复缓存失败 - $url: $e');
      }
    }
  }

  /// 停止所有缓存
  Future<void> _stopAllCaching() async {
    final urls = Set<String>.from(_activeUrls);
    for (final url in urls) {
      try {
        await NativeVideoCacheManager.stopCache(url);
        unregisterActiveUrl(url);
      } catch (e) {
        debugPrint('AppLifecycleManager: 停止缓存失败 - $url: $e');
      }
    }
  }

  /// 释放资源
  void dispose() {
    if (!_isInitialized) return;

    WidgetsBinding.instance.removeObserver(this);
    _backgroundTimer?.cancel();
    _backgroundTimer = null;
    _activeUrls.clear();
    _isInitialized = false;

    debugPrint('AppLifecycleManager: 资源释放完成');
  }

  // Getters
  AppLifecycleState get currentState => _currentState;
  bool get isInBackground => _currentState == AppLifecycleState.paused;
  bool get isInForeground => _currentState == AppLifecycleState.resumed;
  int get activeUrlCount => _activeUrls.length;
}
